package ezonsport.android.service;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import ezonsport.android.common.eventManger.MyEventManager;

import  android.content.Context;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.util.Log;

public class BluetoothService   {

	public enum BTSTATE {
		BLUETOOH_DISABLE,DEVICE_NOTFOUND,SEARCHING,DoPairFail,DoPairSucess,FILE_SENDING,DEVICE_FOUND};
	 public final static  String BLUETOOH_DISABLE="蓝牙未打开";
    public final static  String DEVICE_NOTFOUND="设备未找到";
    public final static  String SEARCHING="查找设备中.....";
    public final static String DoPairFail="配对失败";
    public final static String DoPairSucess="配对成功";
    public final static String FILE_SENDING="发送文件中";
    public final static String DEVICE_FOUND="找到设备";
	private Context context;
	private  BTSTATE state;
    private BluetoothSocket socket; // 蓝牙连接socket
	private BluetoothAdapter mBluetoothAdapter;
	private BroadcastReceiver mScanBluetoothReceiver; // 蓝牙扫描监听器
	
	private BluetoothDevice bluetoothDevice;
 
	public BluetoothService(Context context) {

		this.context=context;

	}




	public void searchDevice() {
		if (null == mBluetoothAdapter) {
			// 取得蓝牙适配器
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		}
		if (!mBluetoothAdapter.isEnabled()) {
			// 蓝牙未打开, 打开蓝牙
			MyEventManager.NotifyEvent(this,BLUETOOH_DISABLE, null);
		
		} else {
		//	state="搜索设备";
			// 蓝牙已打开， 开始搜索设备
			beginDiscovery();
			
			Log.i("BluetoothDemo", "begin");
		}
	}

	public void doPair() {
		if (bluetoothDevice.getBondState() != BluetoothDevice.BOND_BONDED) {	
			initSocket(); // 取得socket
			try {
				socket.connect(); // 请求配对

			} catch (IOException e) {
				Intent data =new Intent();
				data.putExtra("erroInfo", e.getMessage());
				e.printStackTrace();
				MyEventManager.NotifyEvent(this,DoPairFail, data);
				return;
			}
		}
		setState(BTSTATE.DoPairSucess);
		MyEventManager.NotifyEvent(this,DoPairSucess, null);

}

	private void initSocket() {
		BluetoothSocket temp = null;
		try {
		
			// bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(CONNECT_UUID));
			// 以上取得socket方法不能正常使用， 用以下方法代替
			Method m = bluetoothDevice.getClass().getMethod(
					"createRfcommSocket", new Class[] { int.class });
			temp = (BluetoothSocket) m.invoke(bluetoothDevice, 1);
			// 怪异错误： 直接赋值给socket,对socket操作可能出现异常， 要通过中间变量temp赋值给socket
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		socket = temp;
	}

	/**
	 * 开始搜索设备...
	 */
	public void beginDiscovery() {
		//if (null == mProgressDialog) {
		// 注册蓝牙扫描监听器
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
		intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		mBluetoothAdapter.startDiscovery();
		
		 mScanBluetoothReceiver =new BroadcastReceiver() {
			 private List<BluetoothDevice> bluetoothList=new ArrayList<BluetoothDevice>();
			@Override
			public void onReceive(Context context, Intent intent) {
				
				if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
					
					//扫描到蓝牙
				BluetoothDevice   found = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);	
				   bluetoothList.add(found);

				}else if(intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
					context.unregisterReceiver(this);
					//扫描设备结束
					boolean flag=false;
					 if(bluetoothList.size()!=0)
					 {
						for(BluetoothDevice temp: bluetoothList)
						{				
							if(temp.getName().equals("GT-I9300"))
							{	
								bluetoothDevice=temp;
								flag=true;
								setState(BTSTATE.DEVICE_FOUND);
								MyEventManager.NotifyEvent(BluetoothService.this,DEVICE_FOUND, null);
					//			doPair();
							}
							if(flag) break;							
						}								
					 }
					 if(!flag) 
						 MyEventManager.NotifyEvent(this,DEVICE_NOTFOUND, null);
					
				}
				
			}
		};
		context.registerReceiver(mScanBluetoothReceiver,  intentFilter);
		 MyEventManager.NotifyEvent(this,SEARCHING, null);

	}

	/**
	 * 通过蓝牙发送文件
	 */
	public void doSendFileByBluetooth() {
			// 调用系统程序发送文件
			ContentValues cv = new ContentValues();
			String uri = "file://" +"/mnt/sdcard/20120615.txt";
			cv.put("uri", uri);
			cv.put("destination", bluetoothDevice.getAddress());
			cv.put("direction", 0);
			Long ts = System.currentTimeMillis();
			cv.put("timestamp", ts);
			MyEventManager.NotifyEvent(this,FILE_SENDING, null);
			context.getContentResolver().insert(
					Uri.parse("content://com.android.bluetooth.opp/btopp"), cv);
			try {
				if (null != socket) {
					socket.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	}






	public synchronized BTSTATE getState() {
		return state;
	}




	public synchronized void setState(BTSTATE state) {
		this.state = state;
	}

 
	
}
